﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Sripirom.ATS.Core.Logging;

namespace Sripirom.ATS.Core.Validator
{
    /// <summary>
    /// Default error message generation that uses the error messages from the
    /// <see cref="IEnumerable{ValidationResult}"/>
    /// </summary>
    public class ErrorMessageGenerator : IErrorMessageGenerator
    {
        /// <summary>
        /// Generates the error message
        /// </summary>
        /// <param name="operationName">Name of the operaton.</param>
        /// <param name="validationResults">The vlaidation results.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// operationName
        /// or
        /// valdationResults
        /// </exception>
        /// <exception cref="System.ArgumentException">At least one ValidationResult is required</exception>
        public string GenerateErrorMessage(string operationName, IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> validationResults)
        {
            LoggerFactory.CreateLog().Debug("I:GenerateErrorMessage");
            if (operationName == null)
                throw new ArgumentNullException("operationName");

            if (validationResults == null)
                throw new ArgumentNullException("validationResults");

            if (!validationResults.Any())
                throw new ArgumentException("At least one ValidationResult is required");

            var errorMessageBuilder = new StringBuilder();

            errorMessageBuilder.AppendFormat(
                "Service operation {0} failed due to validation errors: {1}{1}",
                operationName,
                Environment.NewLine);

            foreach (var validationResult in validationResults)
            {
                errorMessageBuilder.AppendFormat(
                    "{0} {1}",
                    validationResult.ErrorMessage,
                    Environment.NewLine);
            }

            LoggerFactory.CreateLog().Debug("O:GenerateErrorMessage");

            return errorMessageBuilder.ToString();
        }
    }
}